using System.Collections.Generic;
using UnityEngine;

public class MapViewCarManager : MonoBehaviour
{
	private List<GameObject> cars = new List<GameObject>();

	private Transform top;

	private Transform bottom;

	private float createTopCarTimer;

	private List<MapViewCar> topCars = new List<MapViewCar>();

	private float createBottomCarTimer;

	private List<MapViewCar> bottomCars = new List<MapViewCar>();

	private void Start()
	{
		int childCount = base.transform.childCount;
		for (int i = 0; i < childCount; i++)
		{
			Transform child = base.transform.GetChild(i);
			if (child.name.StartsWith("Car"))
			{
				cars.Add(child.gameObject);
			}
			else if (child.name.Equals("Top"))
			{
				top = child;
			}
			else if (child.name.Equals("Bottom"))
			{
				bottom = child;
			}
		}
		int num = Random.Range(1, 4);
		for (int j = 0; j < num; j++)
		{
			MapViewCar item = CreateNewCar(true, true, top);
			topCars.Add(item);
		}
		createTopCarTimer = Time.realtimeSinceStartup;
		int num2 = Random.Range(1, 4);
		for (int k = 0; k < num2; k++)
		{
			MapViewCar item2 = CreateNewCar(false, true, bottom);
			bottomCars.Add(item2);
		}
		createBottomCarTimer = Time.realtimeSinceStartup;
	}

	private void LateUpdate()
	{
		CreateTopCar();
		CreateBottomCar();
	}

	private MapViewCar CreateNewCar(bool isTop, bool isRandomPosition, Transform parent)
	{
		GameObject gameObject = Object.Instantiate(cars[Random.Range(0, cars.Count)]);
		MapViewCar mapViewCar = gameObject.AddComponent<MapViewCar>();
		mapViewCar.InitCar(this, isTop, isRandomPosition, parent);
		return mapViewCar;
	}

	private void CreateTopCar()
	{
		if (Time.realtimeSinceStartup - createTopCarTimer > 5f)
		{
			if (topCars.Count < 3 && Random.Range(0, 100) > 30)
			{
				topCars.Add(CreateNewCar(true, false, top));
			}
			createTopCarTimer = Time.realtimeSinceStartup;
		}
	}

	private void CreateBottomCar()
	{
		if (Time.realtimeSinceStartup - createBottomCarTimer > 5f)
		{
			if (bottomCars.Count < 3 && Random.Range(0, 100) > 30)
			{
				bottomCars.Add(CreateNewCar(false, false, bottom));
			}
			createBottomCarTimer = Time.realtimeSinceStartup;
		}
	}

	public void RemoveCar(bool isTop, MapViewCar car)
	{
		Object.Destroy(car.gameObject);
		if (isTop)
		{
			topCars.Remove(car);
			CreateTopCar();
		}
		else
		{
			bottomCars.Remove(car);
			CreateBottomCar();
		}
	}
}
